package com.helloworld.core.common.util.sequence;

import java.util.UUID;

public class CouponCodeUtil {
    private static final char[] CODE_POOL = {'z', 'N', 'x', '5', 'h', 'g', 'W', 'b', 'S', '4', 'q', 'X', '7', 'K', 'L', '3', 'a', 'n', 'J', 'P', 'D', 't', 'Z', 'C', 'E', 'A', 'e', 'H', 'M', 'G', 'j', 'Q', 'V', 'Y', 'w', '8', 'f', '2', 'y', 'p', 'u', 'c', 'U', 's', 'd', 'k', 'm', 'B', 'r', 'v', 'T', '6', 'F', 'R', '9'};
    private static final int POOL_SIZE = CODE_POOL.length;
    private static final int[] WEIGHTS = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
    private static final int WEIGHT_SIZE = WEIGHTS.length;

    public static String generateCode() {
        UUID uuid = UUID.randomUUID();
        long uniqueId = uuid.getMostSignificantBits() ^ uuid.getLeastSignificantBits(); // 简单的将两个长整型进行异或操作以生成一个唯一的长整型

        StringBuilder codeBuilder = new StringBuilder();
        int sum = 0;
        int position = -1;

        char currentChar;
        int weight;
        while (uniqueId >= POOL_SIZE) {
            long poolPosition = uniqueId % POOL_SIZE;
            uniqueId /= POOL_SIZE;
            currentChar = CODE_POOL[(int) poolPosition];
            codeBuilder.append(currentChar);

            position++;
            weight = WEIGHTS[position % WEIGHT_SIZE];
            sum += weight * currentChar; // 注意这里Java中字符是Unicode码点，需要转换
        }

        currentChar = CODE_POOL[(int) uniqueId];
        codeBuilder.append(currentChar);

        position++;
        weight = WEIGHTS[position % WEIGHT_SIZE];
        sum += weight * currentChar; // 同样注意字符到整数的转换

        position = sum % POOL_SIZE;
        codeBuilder.append(CODE_POOL[position]);

        return codeBuilder.toString();
    }

    public static boolean Verify(String code) {
        char[] parts = code.toCharArray();
        int sum = 0;
        int weight;
        char part;

        for (int i = 0; i < parts.length - 1; i++) {
            part = parts[i];
            weight = WEIGHTS[i % WEIGHT_SIZE];
            sum += weight * part;
        }

        int position = sum % POOL_SIZE;
        return parts[parts.length - 1] == CODE_POOL[position];
    }

    public static void main(String[] args) {
        System.out.println(generateCode());
    }
}
